package com.qf.utils;

import com.qf.pojo.Menu;
import com.qf.pojo.Usermanager;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.registry.infomodel.User;
import java.io.PrintWriter;
import java.util.List;
import java.util.ResourceBundle;

/**
 * 2019/11/25 0025
 * Author->DT
 * qmxc
 * 行到水穷处 坐看云起时
 * 模块：授权过滤器
 */
//匿名地址是登录前访问的地址；公开地址是指登录后所有人都能访问的地址
public class AuthInterceptor implements HandlerInterceptor {
    //授权拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //前提条件:认证已通过
        //判断是否为匿名地址
        ResourceBundle anon = ResourceBundle.getBundle("anony");
        String requestURI = request.getRequestURI();
        if (anon.containsKey(requestURI)){
            //当前请求地址是匿名地址,放行
            return true;
        }
        //判断是否为公开地址
        ResourceBundle pub = ResourceBundle.getBundle("pub");
        if (pub.containsKey(requestURI)){
            //当前请求地址是公开地址,放行
            return true;
        }
        //判断当前用户是否存在该请求的菜单权限
        Usermanager user = (Usermanager) request.getSession().getAttribute("user");
        List<Menu> menuList = user.getRole().getMenuList();
        for (Menu menu : menuList) {
            List<Menu> secondMenu = menu.getSecondMenu();
            for (Menu menu2 : secondMenu) {
                if (requestURI.equals(menu2.getUrl())){
                    //存在该菜单权限
                    return true;
                }
            }
        }

        //判断当前用户是否存在该请求对应的具体功能请求
        List<Menu> permissionList = user.getRole().getPermissionList();
        for (Menu menu : permissionList) {
            if (requestURI.equals(menu.getUrl())){
                //当前角色存在该功能对应的权限
                return true;
            }
        }

        //授权失败
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print("<script>location.href='/error.jsp'</script>");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
